package com.rest.impl;

import java.io.InputStream;

import com.rest.DeployService;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.util.IOUtils;
import com.util.PathLocator;

public class DeployServiceImpl implements DeployService {

	private final String webappsPath;

	public DeployServiceImpl(String webappsPath) {
		if (webappsPath == null) {
			throw new IllegalArgumentException("webappsPath cannot be null");
		}
		if (!webappsPath.endsWith("/")) {
			webappsPath += "/";
		}
		this.webappsPath = webappsPath;
	}

	@Override
	public String deployWar(InputStream inputStream, FormDataContentDisposition fileDetail, String path) {

		String completePath = PathLocator.getProjectRootPath() + webappsPath;
		if (path != null) {
			completePath += path;
		}
		if (!completePath.endsWith("/")) {
			completePath += "/";
		}

		try {
			IOUtils.saveStreamToFile(inputStream, completePath + fileDetail.getFileName());

		} catch (Exception e) {
			throw new IllegalStateException(String.format("Couldn't deploy file '%s'", fileDetail.getFileName()), e);
		}
		return "Deploy ok";
	}
}
